<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use function fast\array_get;

/**
 * 云途物流收费查询
 *
 * @icon fa fa-circle-o
 */
class Logisticssf extends Backend
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    /**
     * Logisticssf模型对象
     * @var \app\admin\model\Logisticssf
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Logistics;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            $filter = $filter ? $filter : [];
            if (empty($filter['CountryName'])) {
                $this->error('目的地国家不能为空');
            }
            if (empty($filter['Weight'])) {
                $this->error('包裹重量不能为空');
            }
            $where = array();
            if (!empty($filter['CountryName'])) {
                $where['country_name'] = ['like',"%".$filter['CountryName']."%"];
            }
            if (!empty($filter['Weight'])) {
                $filterWeight = $filter['Weight']*1000;
                $where['max_weight'] = array('egt',$filterWeight);
                $where['min_weight'] = array('elt',$filterWeight);
            }
            if (!empty($filter['Length'])) {
                $where['length_limit'] = array('egt',$filter['Length']);
            }
            if (!empty($filter['Width'])) {
                $where['width_limit'] = array('egt',$filter['Width']);
            }
            if (!empty($filter['Height'])) {
                $where['height_limit'] = array('egt',$filter['Height']);
            }
            if (!empty($filter['channel_type'])) {
                $where['channel_type'] = $filter['channel_type'];
            }
            if (!empty($filter['company_name'])) {
                $where['company_name'] = $filter['company_name'];
            }
            $where['status'] = 'normal';

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $lists = $list->items();
            foreach ($lists as $k => $v) {
                //运费
                if ($v['calculation_method'] == 1) {
                    $lists[$k]['FreightFee'] = number_format($v['freight']*$filter['Weight'], 3);
                    $lists[$k]['calculation_formula'] = $lists[$k]['FreightFee'] .'('. $v['freight'] .'x'.$filter['Weight'].')';
                } elseif ($v['calculation_method'] == 2) {

                    if ($filterWeight > 500) {
                        $lists[$k]['FreightFee'] = $v['first_weight_freight'] + $v['continued_weight_freight'];
                        $lists[$k]['calculation_formula'] = $lists[$k]['FreightFee'].'（'.$v['first_weight_freight'].'+'.$v['continued_weight_freight'].'）超过首重0.5KG收费';
                    } else {
                        $lists[$k]['FreightFee'] = $v['first_weight_freight'];
                        $lists[$k]['calculation_formula'] = $v['first_weight_freight'].'（未超过首重0.5KG收费）';
                    }

                }else{
                    $lists[$k]['FreightFee'] = '方式错误';
                }
                //附加运费
                $lists[$k]['FreightFee_additional'] = number_format($v['freight_additional']*$filter['Weight'], 3);
                if ($lists[$k]['FreightFee_additional'] == 0) {
                    $lists[$k]['FreightFee_additional'] = 0;
                }
                if ($lists[$k]['register'] == 0) {
                    $lists[$k]['register'] = 0;
                }
                if ($lists[$k]['service'] == 0) {
                    $lists[$k]['service'] = 0;
                }

                $lists[$k]['FreightFee_additional_formula'] = $lists[$k]['FreightFee_additional'] .'('. $v['freight_additional'] .'x'.$filter['Weight'].')';
                //国内调拨费
                $lists[$k]['transfer'] = 0;
                if ($v['company_name'] == '递四方') {
                    $lists[$k]['transfer'] = number_format(1.8*$filter['Weight'], 3);
                }
                //总运费
                $lists[$k]['TotalFee'] = number_format($lists[$k]['FreightFee'] + $v['register'] + $v['service'] + $v['FreightFee_additional'] + $lists[$k]['transfer'], 3);
                if ($lists[$k]['TotalFee'] == 0) {
                    $lists[$k]['TotalFee'] = 0;
                }
                $lists[$k]['TotalFee_formula'] = $lists[$k]['TotalFee'] .'('. $v['FreightFee'] .'+'.$v['FreightFee_additional'] .'+'.$v['register'] .'+'.$v['service'].'+'.$lists[$k]['transfer'].')';
                if ($v['channel_type'] == 1) {
                    $lists[$k]['channel_type_name'] = '普货';
                }elseif ($v['channel_type'] == 2) {
                    $lists[$k]['channel_type_name'] = '带电';
                }else{
                    $lists[$k]['channel_type_name'] = '未知';
                }
                $lists[$k]['max_limit'] = '长:'.$v['length_limit'].'CM,宽:'.$v['width_limit'].'CM,高:'.$v['height_limit'].'CM';
            }
            $result = array("total" => $list->total(), "rows" => $lists);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                $this->error('重量必须为大于0的数字，最多2位小数');
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    //type 类型 operation具体操作
//                    $this->add_virtualmachine_log(2,$result,1);
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    public function posturl($url,$data = array()){
        $data = (is_array($data)) ? json_encode($data,JSON_UNESCAPED_UNICODE) : $data;
        $headerArray = array("Content-Type:application/json;");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}
